package net.zhuike.novel.app.ui.activity;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;

import net.zhuike.novel.app.R;
import net.zhuike.novel.app.manager.EventManager;
import net.zhuike.novel.app.manager.SettingManager;
import net.zhuike.novel.app.ui.contract.MainContract;
import net.zhuike.novel.app.ui.fragment.BookShelfFragment;
import net.zhuike.novel.app.ui.fragment.BookStoreFragment;
import net.zhuike.novel.app.ui.fragment.SetFragment;
import net.zhuike.novel.app.ui.utils.SharedPreferencesUtil;
import net.zhuike.novel.app.ui.view.readview.GenderPopupWindow;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.OnClick;
import framework.common.baseui.UeBaseActivity;
import framework.common.runtimepermissions.PermissionsManager;
import framework.common.runtimepermissions.PermissionsResultAction;
import framework.common.views.ShouYeViewPager;
import framework.utils.downloader.DownloadService;
import framework.utils.downloader.config.Config;

public class MainActivity extends UeBaseActivity implements View.OnClickListener,MainContract.View{
    private ShouYeViewPager mViewPger;
    private List<Fragment> fragments = new ArrayList<>();
    private BookShelfFragment shelfFragment=new BookShelfFragment();
    private BookStoreFragment storeFragment=new BookStoreFragment();
    private SetFragment setFragment=new SetFragment();
    private LinearLayout footer1,footer2,footer3;
    private RelativeLayout mainLayout;
    private ImageView footer1_img,footer2_img,footer3_img;

    private TextView footer1_text,footer2_text,footer3_text;
    private long currTimemill;
    private GenderPopupWindow genderPopupWindow;
    @Override
    public void loginSuccess() {

    }

    @Override
    public void syncBookShelfCompleted() {
        EventManager.refreshCollectionList();
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_main);
        hiddenHeader();
        MobclickAgent.openActivityDurationTrack(false);
        MobclickAgent.setScenarioType(context, MobclickAgent.EScenarioType.E_DUM_NORMAL);
        initView();
    }
    private void initView(){
        mViewPger = (ShouYeViewPager) findViewById(R.id.mViewPager);
        fragments.add(shelfFragment);
        fragments.add(storeFragment);
        fragments.add(setFragment);
        ViewPagerAdapter mainAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        mViewPger.setAdapter(mainAdapter);
        mViewPger.addOnPageChangeListener(mainAdapter);
        mViewPger.setCurrentItem(0);
        mainLayout=(RelativeLayout)findViewById(R.id.activity_main);
        footer1=(LinearLayout)findViewById(R.id.footer1);
        footer2=(LinearLayout)findViewById(R.id.footer2);
        footer3=(LinearLayout)findViewById(R.id.footer3);
        footer1.setOnClickListener(this);
        footer2.setOnClickListener(this);
        footer3.setOnClickListener(this);
        footer1_img=(ImageView)findViewById(R.id.footer1_img);
        footer2_img=(ImageView)findViewById(R.id.footer2_img);
        footer3_img=(ImageView)findViewById(R.id.footer3_img);
        footer1_text=(TextView)findViewById(R.id.footer1_text);
        footer2_text=(TextView)findViewById(R.id.footer2_text);
        footer3_text=(TextView)findViewById(R.id.footer3_text);
         setTitleText("书架");
        requestPermissions();
        showChooseSexPopupWindow();
        if(!(SharedPreferencesUtil.getInstance().getString("setJson")==null||SharedPreferencesUtil.getInstance().getString("setJson").equals(""))){
            try {
                JSONObject restr = new JSONObject(SharedPreferencesUtil.getInstance().getString("setJson"));
                JSONObject obj=restr.getJSONObject("chapterSetting");
                String fontSizeSetp=obj.getString("fontSizeSetp");
                SharedPreferencesUtil.getInstance().putString("fontSizeSetp",fontSizeSetp);
                String spacings=obj.getString("spacings");
                JSONArray json=new JSONArray(spacings);
                for(int i=0;i<json.length();i++){
                    String jsonValue=json.getString(i);
                    SharedPreferencesUtil.getInstance().putString("spacing"+i,jsonValue);
                }
                String colors=obj.getString("colors");
                JSONArray jsonColor=new JSONArray(colors);
                for(int i=0;i<jsonColor.length();i++){
                    String jsonValue=jsonColor.getString(i);
                    SharedPreferencesUtil.getInstance().putString("colors"+i,jsonValue);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        try {
            Config config = new Config();
            config.setDownloadThread(3);
            config.setEachDownloadThread(2);
            config.setConnectTimeout(10000);
            config.setReadTimeout(10000);
            DownloadService.getDownloadManager(this.getApplicationContext(), config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @TargetApi(23)
    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//				Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {

                //Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("首页");
        MobclickAgent.onResume(context);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("首页");
        MobclickAgent.onPause(context);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.footer1:
                footer1_img.setImageResource(R.mipmap.bar_shelf_hover);
                footer2_img.setImageResource(R.mipmap.bar_store_normal);
                footer3_img.setImageResource(R.mipmap.bar_set_normal);
                footer1_text.setTextColor(Color.parseColor("#1089DC"));
                footer2_text.setTextColor(Color.parseColor("#898989"));
                footer3_text.setTextColor(Color.parseColor("#898989"));
                switchUI(0);
                break;
            case R.id.footer2:
                footer1_img.setImageResource(R.mipmap.bar_shelf_normal);
                footer2_img.setImageResource(R.mipmap.bar_store_hover);
                footer3_img.setImageResource(R.mipmap.bar_set_normal);
                footer1_text.setTextColor(Color.parseColor("#898989"));
                footer2_text.setTextColor(Color.parseColor("#1089DC"));
                footer3_text.setTextColor(Color.parseColor("#898989"));
                switchUI(1);
                break;
            case R.id.footer3:
                footer1_img.setImageResource(R.mipmap.bar_shelf_normal);
                footer2_img.setImageResource(R.mipmap.bar_store_normal);
                footer3_img.setImageResource(R.mipmap.bar_set_hover);
                footer1_text.setTextColor(Color.parseColor("#898989"));
                footer2_text.setTextColor(Color.parseColor("#898989"));
                footer3_text.setTextColor(Color.parseColor("#1089DC"));
                switchUI(2);
                break;
        }
    }

    public class ViewPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener{


        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }

        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private void switchUI(int index){
        switch (index){
            case 0:
                hiddenHeader();
                setTitleText("书架");
                mViewPger.setCurrentItem(0);
                break;
            case 1:
                hiddenHeader();
                setTitleText("书城");
                mViewPger.setCurrentItem(1);
                break;
            case 2:
                hiddenHeader();
                setTitleText("设置");
                mViewPger.setCurrentItem(2);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long time = System.currentTimeMillis();
            if ((time - currTimemill) > 1500) {
                Toast.makeText(this,"再次点击返回退出小说神器",Toast.LENGTH_SHORT).show();
                currTimemill = time;
            } else {
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void setCurrentItem(int position) {
        mViewPger.setCurrentItem(position);
    }
    public void showChooseSexPopupWindow() {
        if (genderPopupWindow == null) {
            genderPopupWindow = new GenderPopupWindow(MainActivity.this);
        }
        if (!SettingManager.getInstance().isUserChooseSex()
                && !genderPopupWindow.isShowing()) {
            mViewPger.postDelayed(()-> {
                genderPopupWindow.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);
            },500);

        }
    }
}
